package com.papercutting.platform.service.impl;

import com.papercutting.platform.dto.request.ChangePasswordRequest;
import com.papercutting.platform.dto.request.LoginRequest;
import com.papercutting.platform.dto.request.ProfileUpdateRequest;
import com.papercutting.platform.dto.request.UserCreateRequest;
import com.papercutting.platform.dto.request.UserUpdateRequest;
import com.papercutting.platform.dto.request.WechatLoginRequest;
import com.papercutting.platform.dto.response.LoginResponse;
import com.papercutting.platform.dto.response.UserResponse;
import com.papercutting.platform.entity.User;
import com.papercutting.platform.service.AuthService;
import com.papercutting.platform.service.UserService;
import com.papercutting.platform.util.EntityConverter;
import com.papercutting.platform.util.JwtUtil;
import com.papercutting.platform.util.PasswordUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;

/**
 * 认证服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    
    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Value("${app.wechat.app-id}")
    private String wechatAppId;
    
    @Value("${app.wechat.app-secret}")
    private String wechatAppSecret;
    
    @Value("${app.jwt.expiration:86400000}")
    private Long jwtExpiration;
    
    @Override
    public LoginResponse login(LoginRequest request) {
        log.info("用户登录: {}", request.getUsername());
        
        // 验证用户凭据 - 委托给UserService处理
        UserResponse userResponse = userService.authenticate(request.getUsername(), request.getPassword());
        
        if (userResponse == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 生成JWT token（包含用户类型）
        String token = jwtUtil.generateToken(userResponse.getId(), userResponse.getNickname(), userResponse.getUserType());
        
        log.info("用户登录成功: {}", request.getUsername());
        
        return LoginResponse.of(token, userResponse, jwtExpiration / 1000);
    }
    
    @Override
    @Transactional
    public LoginResponse wechatLogin(WechatLoginRequest request) {
        log.info("微信登录请求: {}", request.getCode());
        
        // 调用微信接口获取openId
        String openId = getOpenIdFromWechat(request.getCode());
        if (!StringUtils.hasText(openId)) {
            throw new RuntimeException("微信登录验证失败");
        }
        
        // 查找或创建用户
        User user = userService.findByOpenId(openId);
        
        if (user == null) {
            // 创建新用户
            user = createUserFromWechatInfo(openId, request.getUserInfo());
        } else {
            // 更新用户信息
            updateUserFromWechatInfo(user, request.getUserInfo());
        }
        
        // 转换为响应DTO
        UserResponse userResponse = EntityConverter.toUserResponse(user);
        
        // 生成JWT token（包含用户类型）
        String token = jwtUtil.generateToken(user.getId(), user.getNickname(), user.getUserType());
        
        log.info("微信登录成功: {}", user.getNickname());
        
        return LoginResponse.of(token, userResponse, jwtExpiration / 1000);
    }
    
    @Override
    @Transactional
    public LoginResponse register(UserCreateRequest request) {
        log.info("用户注册: {}", request.getNickname());
        
        // 创建用户 - 委托给UserService处理（包含重复检查）
        Long userId = userService.createUser(request);
        
        // 获取创建的用户
        UserResponse userResponse = userService.getUserById(userId);
        
        // 生成JWT token（包含用户类型）
        String token = jwtUtil.generateToken(userId, userResponse.getNickname(), userResponse.getUserType());
        
        log.info("用户注册成功: {}", request.getNickname());
        
        return LoginResponse.of(token, userResponse, jwtExpiration / 1000);
    }
    
    @Override
    public UserResponse getUserInfoByToken(String token) {
        // 解析token获取用户ID
        Long userId = jwtUtil.getUserIdFromToken(token);
        
        if (userId == null) {
            throw new RuntimeException("无效的token");
        }
        
        UserResponse userResponse = userService.getUserById(userId);
        
        if (userResponse == null) {
            throw new RuntimeException("用户不存在");
        }
        
        return userResponse;
    }
    
    @Override
    @Transactional
    public UserResponse updateCurrentUser(String token, UserUpdateRequest request) {
        // 解析token获取用户ID
        Long userId = jwtUtil.getUserIdFromToken(token);

        if (userId == null) {
            throw new RuntimeException("无效的token");
        }

        request.setId(userId);
        userService.updateUser(request);

        return userService.getUserById(userId);
    }

    @Override
    @Transactional
    public UserResponse updateProfile(String token, ProfileUpdateRequest request) {
        log.info("更新个人资料请求");

        // 解析token获取用户ID
        Long userId = jwtUtil.getUserIdFromToken(token);

        if (userId == null) {
            throw new RuntimeException("无效的token");
        }

        // 转换为UserUpdateRequest
        UserUpdateRequest userUpdateRequest = new UserUpdateRequest();
        userUpdateRequest.setId(userId);
        userUpdateRequest.setNickname(request.getNickname());
        userUpdateRequest.setPhone(request.getPhone());
        userUpdateRequest.setEmail(request.getEmail());
        userUpdateRequest.setAvatarUrl(request.getAvatarUrl());
        userUpdateRequest.setGender(request.getGender());
        userUpdateRequest.setCountry(request.getCountry());
        userUpdateRequest.setProvince(request.getProvince());
        userUpdateRequest.setCity(request.getCity());
        userUpdateRequest.setLanguage(request.getLanguage());
        userUpdateRequest.setRemark(request.getRemark());

        userService.updateUser(userUpdateRequest);

        log.info("个人资料更新成功，用户ID: {}", userId);
        return userService.getUserById(userId);
    }

    @Override
    @Transactional
    public void changePassword(String token, ChangePasswordRequest request) {
        log.info("修改密码请求");

        // 解析token获取用户ID
        Long userId = jwtUtil.getUserIdFromToken(token);

        if (userId == null) {
            throw new RuntimeException("无效的token");
        }

        // 获取当前用户
        User user = userService.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证当前密码
        if (!PasswordUtil.matches(request.getCurrentPassword(), user.getPassword())) {
            throw new RuntimeException("当前密码不正确");
        }

        // 更新密码
        user.setPassword(PasswordUtil.encode(request.getNewPassword()));
        user.setUpdateTime(LocalDateTime.now());
        userService.save(user);

        log.info("用户密码修改成功，ID: {}", userId);
    }

    @Override
    public LoginResponse refreshToken(String refreshToken) {
        // TODO: 实现token刷新逻辑
        throw new RuntimeException("暂未实现token刷新功能");
    }

    @Override
    public void logout(String token) {
        // TODO: 实现登出逻辑（可能需要token黑名单）
        log.info("用户登出");
    }
    
    /**
     * 调用微信接口获取OpenId
     */
    private String getOpenIdFromWechat(String code) {
        try {
            String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                wechatAppId, wechatAppSecret, code
            );
            
            String response = restTemplate.getForObject(url, String.class);
            
            // 简化的JSON解析（实际项目应使用Jackson等JSON库）
            if (StringUtils.hasText(response) && response.contains("\"openid\"")) {
                int start = response.indexOf("\"openid\":\"") + 10;
                int end = response.indexOf("\"", start);
                if (start > 9 && end > start) {
                    return response.substring(start, end);
                }
            }
            
            log.error("微信API返回异常: {}", response);
            return null;
        } catch (Exception e) {
            log.error("调用微信API失败", e);
            return null;
        }
    }
    
    /**
     * 从微信信息创建新用户
     */
    private User createUserFromWechatInfo(String openId, WechatLoginRequest.WechatUserInfo wechatUserInfo) {
        UserCreateRequest request = new UserCreateRequest();
        request.setNickname(wechatUserInfo.getNickname());
        request.setAvatarUrl(wechatUserInfo.getAvatarUrl());
        request.setGender(wechatUserInfo.getGender());
        request.setCountry(wechatUserInfo.getCountry());
        request.setProvince(wechatUserInfo.getProvince());
        request.setCity(wechatUserInfo.getCity());
        request.setLanguage(wechatUserInfo.getLanguage());
        
        // 创建用户实体
        User user = EntityConverter.toUser(request);
        user.setOpenId(openId);
        user.setLastLoginTime(LocalDateTime.now());
        
        // TODO: 这里需要直接插入数据库，或者扩展UserService的createUser方法
        // 暂时简化处理
        
        return user;
    }
    
    /**
     * 从微信信息更新用户
     */
    private void updateUserFromWechatInfo(User user, WechatLoginRequest.WechatUserInfo wechatUserInfo) {
        user.setNickname(wechatUserInfo.getNickname());
        user.setAvatarUrl(wechatUserInfo.getAvatarUrl());
        user.setGender(wechatUserInfo.getGender());
        user.setCountry(wechatUserInfo.getCountry());
        user.setProvince(wechatUserInfo.getProvince());
        user.setCity(wechatUserInfo.getCity());
        user.setLanguage(wechatUserInfo.getLanguage());
        user.setLastLoginTime(LocalDateTime.now());
        
        // TODO: 更新到数据库
        // userService.updateUser(...);
    }
}